package com.zjbbkj.baibai.netty.message.receive;

import com.alibaba.fastjson.TypeReference;
import com.zjbbkj.baibai.common.utils.wanli.MyUtils;
import com.zjbbkj.baibai.common.utils.wanli.RedisCacheUtil;
import com.zjbbkj.baibai.domain.device.Device;
import com.zjbbkj.baibai.netty.feign.DeviceFeignService;
import com.zjbbkj.baibai.netty.maps.ContainerMaps;
import com.zjbbkj.baibai.netty.message.factory.Operation;
import io.netty.channel.Channel;
import lombok.extern.slf4j.Slf4j;
import javax.annotation.Resource;
import java.util.Map;
import static com.zjbbkj.baibai.netty.message.factory.OperatorFactory.addInstance;

/**
 * @Description IMEIID处理
 * @author WanLi
 * @date 2021年08月24日 17:32
 */
@Slf4j
public class ReceiveADV implements Operation {

    @Resource
    private RedisCacheUtil redisCacheUtil;

    @Resource
    private DeviceFeignService deviceFeignService;

    @Override
    public void parsingMsg(String message, Channel channel) {
        Map<String, Channel> channels = ContainerMaps.getChannels();
        Map<Channel, String> channelsX = ContainerMaps.getChannelsX();
        try {
            if (!MyUtils.isNull(message)) {
                String IMEIID = message.substring(19);
                if (channels.containsKey(IMEIID)) {
                    Channel c = channels.get(IMEIID);
                    ContainerMaps.removeGatewayChannel(IMEIID);
                    if (channelsX.containsKey(c)) {
                        ContainerMaps.removeGatewayChannelX(c);
                    }
                }else{
                    //查询是否有此设备
                    Device device = deviceFeignService.getDevice(IMEIID).getData("device",new TypeReference<Device>(){});
                    //初始化设备
                    if(MyUtils.isNull(device)){
                        deviceFeignService.insertDevice(IMEIID);
                    }
                }

                //System.out.println("IMEIID:" + IMEIID);
                //存入redis缓存
                //初始化设备
                //DeviceService deviceService = SpringUtils.getBean(DeviceService.class);
                //Device device = deviceService.getDevice(IMEIID);
                //                    if (MyUtils.isNull(device)) {
                //                        initDevice(IMEIID);
                //                    }

                addInstance(IMEIID, channel);
            }
        } catch (Exception e) {
            log.info(e.getMessage());
        }
    }
}
